<?php

namespace App\Model;

use EasySwoole\DDL\Enum\Character;
use EasySwoole\DDL\Enum\Engine;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\ORM\Utility\Schema\Table;
use Throwable;

class ShopDiscountModel extends AbstractModel
{
    protected $tableName = 't_shop_discount';
    protected $autoTimeStamp = true; // 自动写入create_time和update_time 这两个字段是int

    /**
     * @throws Exception
     * @throws Throwable
     * @throws Exception|Throwable
     */
    public function getDiscount($where)
    {
        $where['is_deleted'] = 0;
        return $this->order('id', 'desc')->get($where);
    }

    /**
     * @throws Throwable
     * @throws Exception
     */
    public function addDiscount($where)
    {
        $this->data($where, false);
        return $this->save();
    }

    public function schemaInfo(bool $isCache = true): Table
    {
        $table = new Table($this->tableName);

        $table->setIfNotExists();
        $table->setTableEngine(Engine::INNODB);
        $table->setTableCharset(Character::UTF8MB4_GENERAL_CI);
        $table->setTableComment('数据-商品-折扣');

        $table->colInt('id')->setIsAutoIncrement()->setIsPrimaryKey(true)->setColumnComment("ID");
        $table->colInt('sid', 25)->setDefaultValue(0)->setIsNotNull()->setColumnComment('商户id');
        $table->colVarChar('name', 50)->setDefaultValue('')->setColumnComment('方案名称');
        $table->colTinyInt('type',2)->setColumnComment(0)->setColumnComment('满足条件类型：0.金额，1.数量');
        $table->colVarChar('num',10)->setDefaultValue('')->setColumnComment('满足金额或者数量');
        $table->colTinyInt('discount_type',2)->setColumnComment(0)->setColumnComment('折扣类型：0.减少金额,1.折扣');
        $table->colDecimal('discount',10,2)->setDefaultValue(0.00)->setColumnComment('减免金额或者折扣');
        $table->colBigInt('sort', 20)->setDefaultValue(0)->setColumnComment('列表排序权重');
        $table->colTinyInt('status',1)->setDefaultValue(1)->setColumnComment('商品状态(1使用,0禁用)');
        $table->colTinyInt('is_deleted', 1)->setDefaultValue(0)->setIsNotNull()->setColumnComment('是否删除：0.未删除，1.已删除');
        $table->colInt('create_time', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('创建时间戳');
        $table->colInt('update_time', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('更新时间戳');

        $table->indexNormal('type_index', 'type');
        $table->indexNormal('discount_type_index', 'discount_type');
        $table->indexNormal('idx_base_postage_company_status', 'status');
        $table->indexNormal('idx_base_postage_company_deleted', 'is_deleted');
        return $table;
    }
}